package com.aat.dxfy.sync;

import java.awt.Color;
import java.awt.Font;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.UnsupportedLookAndFeelException;

public class SyncFilesFrame extends JFrame implements ActionListener {
	private static final long serialVersionUID = 1L;
	private int x = Toolkit.getDefaultToolkit().getScreenSize().width;
	private int y = Toolkit.getDefaultToolkit().getScreenSize().height;
	private int w = x / 2;
	private int h = y / 2;

	// UI
	private LookAndFeelInfo[] look;
	private Font font = new Font("微软雅黑", 10, 15);

	// 组件
	private JPanel jp;
	private JLabel jl1 = new JLabel("1，选择同步目录A");
	private JTextField jtf = new JTextField("");
	private JLabel jl2 = new JLabel("2，选择同步目录B");
	private JTextField jtf2 = new JTextField("");
	private JButton jbtnA = new JButton("选择A");
	private JButton jbtn = new JButton("选择B");
	private JButton jb2 = new JButton("执行");
	private JButton jb3 = new JButton("取消");
	//
	private String str1, str2;

	public SyncFilesFrame() {
		super("目录文件同步");
		//this.setIconImage(Toolkit.getDefaultToolkit().createImage(getClass().getResource("/com/aat/dxfy/sync/logo.png")));
		// 添加组件
		this.setBounds(w / 2, h / 2, w, h);
		this.setLayout(null);
		jp = new JPanel(null);
		jp.setBounds(0, 0, w, h);
		jp.setBackground(new Color(0XF0, 0XF0, 0xF0));// #F77B6F
		// 1
		jl1.setFont(font);
		jl1.setBounds(w / 4, h / 6 - 50, w / 2, h / 10);
		jp.add(jl1);
		// 1
		jtf.setFont(font);
		jtf.setBounds(w / 4, h / 6, w / 2, h / 10);
		jtf.setEditable(false);
		jp.add(jtf);

		// 1.5

		jbtnA.setFont(font);
		jbtnA.setBounds(w / 4, h / 6 + 50, 200, h / 10);
		jp.add(jbtnA);
		// 2
		jl2.setFont(font);
		jl2.setBounds(w / 4, h / 6 + 100, w / 2, h / 10);
		jp.add(jl2);
		// 2
		jtf2.setFont(font);
		jtf2.setBounds(w / 4, h / 6 + 150, w / 2, h / 10);
		jtf2.setEditable(false);
		jp.add(jtf2);
		jbtn.setFont(font);
		jbtn.setBounds(w / 4, h / 6 + 200, 200, h / 10);
		jp.add(jbtn);

		// 3
		jb2.setFont(font);
		jb2.setBounds(w / 4, h / 6 + 250, 100, h / 10);
		jp.add(jb2);

		// 3
		jb3.setFont(font);
		jb3.setBounds(w / 4 + 150, h / 6 + 250, 100, h / 10);
		jp.add(jb3);

		//
		jbtn.addActionListener(this);
		jbtnA.addActionListener(this);
		jb3.addActionListener(this);
		jb2.addActionListener(this);
		this.add(jp);
		// ///////////
		try {
			look = UIManager.getInstalledLookAndFeels();
			UIManager.setLookAndFeel(look[1].getClassName());
			SwingUtilities.updateComponentTreeUI(this);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (UnsupportedLookAndFeelException e) {
			e.printStackTrace();
		}
		// this.setUndecorated(true);
		this.setVisible(true);
		this.setResizable(false);// 不放大
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}

	public void actionPerformed(ActionEvent e) {
		if (e.getSource() == jbtn) {
			JFileChooser jfc = new JFileChooser();
			jfc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
			// jfc.showDialog(new JLabel(), "选择");
			int returnVal = jfc.showOpenDialog(this);
			if (returnVal == JFileChooser.APPROVE_OPTION) {
				File file = jfc.getSelectedFile();
				if (file.isDirectory()) {
					String fp = file.getAbsolutePath();
					jtf2.setText(fp);
				} else {
					jtf2.setText("");
				}
			} else {
				JOptionPane.showMessageDialog(null, "请选择目录", "提示消息", JOptionPane.INFORMATION_MESSAGE);
			}
		}

		if (e.getSource() == jbtnA) {
			JFileChooser jfc = new JFileChooser();
			jfc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
			// jfc.showDialog(new JLabel(), "选择");
			int returnVal = jfc.showOpenDialog(this);
			if (returnVal == JFileChooser.APPROVE_OPTION) {
				File file = jfc.getSelectedFile();
				if (file.isDirectory()) {
					String fp = file.getAbsolutePath();
					jtf.setText(fp);
				} else {
					jtf.setText("");
				}
			} else {
				JOptionPane.showMessageDialog(null, "请选择目录", "提示消息", JOptionPane.INFORMATION_MESSAGE);
			}
		}

		if (e.getSource() == jb2) {
			str1 = jtf2.getText();
			str2 = jtf.getText();
			if (null == str1 || null == str2 || str1.length() == 0 || str2.length() == 0) {
				JOptionPane.showMessageDialog(null, "请选择目录", "提示消息", JOptionPane.INFORMATION_MESSAGE);
			} else {
				// 执行业务
				String dirA=str1;
				String dirB=str2;
				
				try {
					//正向
					chkFiles(dirA);
					doSync(dirA, dirB);
					//反向
					lists.clear();
					chkFiles(dirB);
					doSync(dirB, dirA);
				} catch (IOException e1) {
					e1.printStackTrace();
				}
				//
				JOptionPane.showMessageDialog(null, "同步完毕！", "提示消息", JOptionPane.INFORMATION_MESSAGE);
			}
			//
		}

		if (e.getSource() == jb3) {
			System.exit(0);
		}
	}

	public static void main(String[] args) {
		new SyncFilesFrame();
	}

	public List<Map<String, Long>> lists = new ArrayList<Map<String, Long>>();

	public void doSync(String dirA, String dirB) throws IOException {
		for (Map<String, Long> map : lists) {
			Set<Entry<String, Long>> set = map.entrySet();
			String apath = set.iterator().next().getKey();
			Long aTime = set.iterator().next().getValue();
			String aFilePath = apath.substring(apath.indexOf(dirA) + dirA.length(), apath.length());
			String bFilePath = dirB + aFilePath;
			File bFile = new File(bFilePath);
			if (bFile.exists()) {
				Long bTime = bFile.lastModified();
				if (aTime > bTime) {
					// A->B
					copyFileAtoB(apath, bFilePath);
				} else {
					// B->A
					copyFileAtoB(bFilePath, apath);
				}
			} else {
				// A->B
				copyFileAtoB(apath, bFilePath);
			}
		}
	}

	// 列出文件
	public void chkFiles(String dirA) {
		File filesA = new File(dirA);
		File[] files = filesA.listFiles();
		for (File file : files) {
			if (file.isDirectory()) {
				chkFiles(file.getAbsolutePath());
			} else {
				String filePath = file.getAbsolutePath();
				Long fileTime = file.lastModified();
				Map<String, Long> map = new HashMap<String, Long>();
				map.put(filePath, fileTime);
				lists.add(map);
			}
		}
	}

	// 进行拷贝
	public void copyFileAtoB(String fileA, String fileB) throws IOException {
		File file = new File(fileB);
		if (!file.exists()) {
			String fileP = file.getParent();
			File f = new File(fileP);
			f.mkdirs();
		}
		InputStream in = new FileInputStream(fileA);
		OutputStream out = new FileOutputStream(fileB);
		byte[] bs = new byte[102400];
		int i = -1;
		while ((i = in.read(bs)) > 0) {
			out.write(bs, 0, i);
		}
		out.flush();
		in.close();
		out.close();
	}

}
